package com.jzwl.system.admin.user.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jzwl.system.admin.sysuser.service.SysuserService;
import com.jzwl.system.admin.user.service.BusyShopuserService;
import com.jzwl.system.base.controller.BaseController;
import com.jzwl.common.constant.Constants;
import com.jzwl.common.page.PageObject;
import com.jzwl.common.utils.StringUtil;
import com.jzwl.common.utils.Util;

@Controller
@RequestMapping(value = "/login")
public class LoginController extends BaseController {

	@Autowired
	private BusyShopuserService busyShopuserService;
	@Autowired
	private SysuserService sysuserService;
	@Autowired
	private Constants constants;

	private static Logger log = LoggerFactory.getLogger(LoginController.class);

	@RequestMapping("/sessionTimeout")
	public String sessionTimeout(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		boolean flag = false;
		String agent = request.getHeader("User-Agent");
		flag = Util.isMobPlat(agent);

		try {
			if (request.getHeader("x-requested-with") != null
					&& request.getHeader("x-requested-with").equalsIgnoreCase(
							"XMLHttpRequest")) { // ajax 超时处理
				response.setStatus(response.SC_FORBIDDEN);
				PrintWriter out = response.getWriter();
				out.print("Session Timeout!");
				out.flush();
				out.close();
				return null;
			} else { // http 超时处理
				if (flag) {// 移动端
					/* 版本v1.0 return "redirect:/skillUser/toAddSkillUser.html";*/
					//2.0版本session失效将跳转到首页
					log.error("-----当前为移动端session失效跳转-----");
					/*return null;*/
					return "redirect:/home/index.html";
				} 
				log.error("-----当前为PC端session失效跳转-----");
				return "redirect:/login.jsp";
			}
		} catch (Exception e) {
			log.error("session 失效跳转异常",e);
			e.printStackTrace();
			if (flag) {// 移动端
				/* 版本v1.0 return "redirect:/skillUser/toAddSkillUser.html";*/
				return "redirect:/home/index.html";
			} 
			return "redirect:/login.jsp";

		}

	}

	/**
	 * 2.0版本登录页的跳转
	 */
	@RequestMapping("/toindex")  
    public String toIndex(HttpServletRequest request,HttpServletResponse response) throws IOException {  
		//ModelAndView mv = new ModelAndView();
		//mv.setViewName("/indexv2");
		String name = getCurrentUserName();
		if (StringUtil.isEmptyOrBlank(name)) {
			request.setAttribute("msg", "用户名或密码错误！");
			return "/error";
		}
		Map<String, Object> user = null;
		try {
			user = sysuserService.findUserByName(name);
			if (user == null) {
				request.setAttribute("msg", "用户名或密码错误！");
				return "/error";
			}
			Map roleMap = sysuserService.findRolerByUserId(String.valueOf(user.get("id")));
			if(null!=roleMap){
				request.getSession().setAttribute("roleName", roleMap.get("name"));
			}
			request.getSession().setAttribute("citycode", user.get("citycode"));
			request.getSession().setAttribute("departmentId", user.get("departmentId"));
			request.getSession().setAttribute("userName",user.get("username"));
		} catch (Exception e) {
			request.setAttribute("msg", "用户名或密码错误！");
			return "/error";
		}
		request.getSession().setAttribute("user",user);
		List<Map<String, Object>> privileges = null;
		try {
			privileges = sysuserService.findPrivilegesByUserId(String.valueOf(user.get("id")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map map = new HashMap();
		for (Map<String, Object> privilege : privileges) {
			map.put(privilege.get("authorityId"), privilege.get("authorityCode"));
		}
		request.getSession().setAttribute("privilege", map);
		request.getSession().setAttribute("user", user);
		return "/base/index";
	} 
	
	/**
	 * 2.0版本退出系统
	 */
	@RequestMapping("/exit")  
    public String exit(HttpServletRequest request,HttpServletResponse response){
		request.getSession().invalidate();
		return "redirect:/login.jsp";
	}
	
	/**
	 * 修改密码
	 */
	@RequestMapping("/updatePass")
	public String updatePass(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		createParameterMap(request);
		PageObject po = new PageObject();
		paramsMap.put("isDelete", 0);
		try {
			po = sysuserService.querySysuserList(paramsMap);
			model.addAttribute("po", po);
			model.addAttribute("paramsMap", paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "获取数据失败");
			return "/error";
		}
		return "/base/system/updatePass";
	}
}